package com.zm.campus.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import java.util.Random;


/*  用户输入密码后，前端进行第一次md5加密，然后传给后端，后端再进行一次加密传给数据库（传包含加密后的密码，和加密所用的salt）
* */
@Component
public class MD5Util {
    //md5加密
    public static String toMD5(String src){
        return DigestUtils.md5Hex(src);
    }
    //字符串用于给加密时取对应字符
    private static final String salt="H8gMu1";
    //随机盐生成器
    public static String getSalt(int n){
        char[] chars=("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"+"1234567890!@#$%^&*(),._+;[]").toCharArray();
        StringBuilder stringBuilder=new StringBuilder();
        for (int i = 0; i <n ; i++) {
            char c=chars[new Random().nextInt(chars.length)];
            stringBuilder.append(c);
        }
        return stringBuilder.toString();
    }
    //第一次md5加密
    public static String inputPassToFromPass(String inputPass,String salt){
        String first=""+salt.charAt(0)+salt.charAt(3)+inputPass+salt.charAt(5);
        return toMD5(first);
    }
    //第二次md5加密
    public static String fromPassTODBPass(String fromPass,String salt){
        String second=""+salt.charAt(1)+salt.charAt(2)+fromPass+salt.charAt(4);
        return toMD5(second);
    }

    //用户真正调用的加密方法
    public static String inputPassToDBPass(String inputPass,String salt){
        String fromPass = inputPassToFromPass(inputPass,salt);
        String dbPass = fromPassTODBPass(fromPass, salt);
        return dbPass;
    }

    public static void main(String[] args) {
        System.out.println("第一次加密："+inputPassToFromPass("202025040238",salt));//2d699d09d71334432425755e757c44cb
        System.out.println("第二次加密："+fromPassTODBPass(inputPassToFromPass("202025040238",salt),salt));//1dbd679b38cadbab28ba769f671dbe79
        System.out.println("完整加密："+inputPassToDBPass("202025040238",salt));//1dbd679b38cadbab28ba769f671dbe79
    }

}
